//
//  DR_AddActionSheet.swift
//  DocReaderRP
//
//  Created by  mac on 2025/11/10.
//

import UIKit
import SnapKit

class DR_AddActionSheet: UIView {
    
    var onFileImportTapped: (() -> Void)?
    var onDismiss: (() -> Void)?
    
    private let backgroundView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        return view
    }()
    
    private let containerView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.layer.cornerRadius = 30
        view.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
        return view
    }()
    
    private let titleLabel: UILabel = {
        let label = UILabel()
        label.text = "add_title".localized
        label.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        label.textColor = .black
        label.textAlignment = .center
        return label
    }()
    
    private let fileImportButton: UIButton = {
        let button = UIButton(type: .custom)
        button.backgroundColor = "#EBECFF".toColor
        button.layer.cornerRadius = 16
        return button
    }()
    
    private let folderIconView: UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "add_file")
        imageView.contentMode = .scaleAspectFit
        return imageView
    }()
    
    private let fileImportLabel: UILabel = {
        let label = UILabel()
        label.text = "add_title".localized
        label.font = UIFont.systemFont(ofSize: 14)
        label.textColor = "#333FFF".toColor
        return label
    }()
    
    private let uploadIconView: UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "add_upload")
        imageView.contentMode = .scaleAspectFit
        return imageView
    }()
    
    private let closeButton: UIButton = {
        let button = UIButton(type: .custom)
        button.backgroundColor = UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 1.0)
        button.layer.cornerRadius = 20
        let xmarkImage = UIImage(systemName: "xmark")
        button.setImage(xmarkImage, for: .normal)
        button.tintColor = .black
        button.imageView?.contentMode = .scaleAspectFit
        return button
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        setupConstraints()
        setupActions()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        addSubview(backgroundView)
        addSubview(containerView)
        
        containerView.addSubview(titleLabel)
        containerView.addSubview(fileImportButton)
        
        fileImportButton.addSubview(folderIconView)
        fileImportButton.addSubview(fileImportLabel)
        fileImportButton.addSubview(uploadIconView)
        
        containerView.addSubview(closeButton)
    }
    
    private func setupConstraints() {
        backgroundView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        containerView.snp.makeConstraints { make in
            make.leading.trailing.bottom.equalToSuperview()
            make.height.equalTo(205)
        }
        
        titleLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(24)
        }
        
        fileImportButton.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview().inset(20)
            make.top.equalTo(titleLabel.snp.bottom).offset(24)
            make.height.equalTo(60)
        }
        
        folderIconView.snp.makeConstraints { make in
            make.centerY.top.bottom.equalToSuperview()
            make.width.equalTo(60)
        }
        
        fileImportLabel.snp.makeConstraints { make in
            make.leading.equalTo(folderIconView.snp.trailing).offset(12)
            make.centerY.equalToSuperview()
        }
        
        uploadIconView.snp.makeConstraints { make in
            make.trailing.equalToSuperview().offset(-16)
            make.centerY.equalToSuperview()
            make.width.height.equalTo(24)
        }
        
        closeButton.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(fileImportButton.snp.bottom).offset(24)
            make.width.height.equalTo(40)
            make.bottom.lessThanOrEqualToSuperview().offset(-20)
        }
    }
    
    private func setupActions() {
        backgroundView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(dismiss)))
        fileImportButton.addTarget(self, action: #selector(fileImportButtonTapped), for: .touchUpInside)
        closeButton.addTarget(self, action: #selector(dismiss), for: .touchUpInside)
    }
    
    @objc private func fileImportButtonTapped() {
        dismiss()
        onFileImportTapped?()
    }
    
    @objc private func dismiss() {
        hide()
    }
    
    func show(in parentView: UIView) {
        parentView.addSubview(self)
        // 确保弹窗在最上层
        parentView.bringSubviewToFront(self)
        
        self.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            self.topAnchor.constraint(equalTo: parentView.topAnchor),
            self.leadingAnchor.constraint(equalTo: parentView.leadingAnchor),
            self.trailingAnchor.constraint(equalTo: parentView.trailingAnchor),
            self.bottomAnchor.constraint(equalTo: parentView.bottomAnchor)
        ])
        
        // 初始状态：背景透明，容器在底部外
        backgroundView.alpha = 0
        containerView.transform = CGAffineTransform(translationX: 0, y: 250)
        
        // 强制布局
        layoutIfNeeded()
        
        // 再次确保弹窗在最上层（布局后）
        parentView.bringSubviewToFront(self)
        
        // 动画显示
        UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut) {
            self.backgroundView.alpha = 1
            self.containerView.transform = .identity
        } completion: { _ in
            // 动画完成后再次确保在最上层
            parentView.bringSubviewToFront(self)
        }
    }
    
    func hide() {
        UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseIn) {
            self.backgroundView.alpha = 0
            self.containerView.transform = CGAffineTransform(translationX: 0, y: 250)
        } completion: { _ in
            self.removeFromSuperview()
            self.onDismiss?()
        }
    }
}
